package dbinfo

import (
	"context"
	"fmt"
	"log"
	"strings"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"spider.com/day/settings"
)

var MongoClient *mongo.Client // 声明全局 MongoDB 客户端变量

var CollectionStock *mongo.Collection
var CollectionDayLine *mongo.Collection

func ConnectToMongoDB() {
    // 设置客户端选项
    clientOptions := options.Client().ApplyURI("mongodb://admin:123456@localhost:27017") // 替换为你的 MongoDB URI

    // 连接到 MongoDB
    var err error
    MongoClient, err = mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
        log.Fatal(err)
    }

    // 检查连接
    err = MongoClient.Ping(context.TODO(), nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")
	CollectionStock = MongoClient.Database("board").Collection("stocks")
	CollectionDayLine = MongoClient.Database("board").Collection("day_line")
}

func SaveToMongo(klineChan chan *settings.DayStock, collection *mongo.Collection) {
	opts := options.Update().SetUpsert(true)
	for {
		stockDay, ok := <-klineChan
		if !ok {
			break
		}
		filter := bson.M{"symbol": stockDay.Symbol}
		update := bson.M{"$set": stockDay}
		_, err := collection.UpdateOne(context.TODO(), filter, update, opts)
		if err != nil {
			log.Println(err)
		}

		// if result.UpsertedID != nil {
		// 	log.Println("Inserted a new document with ID:", result.UpsertedID, stock.Symbol)
		// } else {
		// 	log.Println("Updated an existing document.", stock.Symbol)
		// }
	}
}

func PutStockFromMongo(ctx context.Context, stockChan chan settings.Stock, collection *mongo.Collection) {
	stocksCursor, err := collection.Find(ctx, map[string]interface{}{"exist": 1})
	if err != nil {
		log.Fatal(err)
	}
	defer stocksCursor.Close(ctx)

	for stocksCursor.Next(ctx) {
		var stock settings.Stock
		if err := stocksCursor.Decode(&stock); err != nil {
			log.Fatal(err)
		}
		// log.Println(stock)
		if !strings.Contains(stock.Name, "ST") || !strings.Contains(stock.Name, "*") {
			stockChan <- stock
		}

	}
}